<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>数据表格的重载 - 数据表格</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="{{ADMIN_PATH}}layui/layuiadmin/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="{{ADMIN_PATH}}layui/layuiadmin/style/admin.css" media="all">
    <link rel="stylesheet" href="{{ADMIN_PATH}}ztree/css/zTreeStyle/zTreeStyle.css" media="all">
    <style>
        .ztree .node_name {
            font-style: normal;
            font-variant: normal;
            font-weight: normal;
            font-stretch: normal;
            font-size: 14px;
            font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 微软雅黑, Tahoma, Arial, sans-serif;
        }

        .ztree li {
            line-height: 28px;
        }

        .ztree li a {
            height: 28px;
            color: #666;
            font-weight: normal;
        }

        .ztree li a:hover {
            text-decoration: none;
            color: #FF5722;
        }

        .ztree li a.curSelectedNode {
            padding: 1px 3px 0 0;
            margin: 0;
            cursor: pointer;
            vertical-align: top;
            display: inline-block;
            height: 28px;
            border: none;
            background-color: #F0F0F0;
            color: #FF5722;
        }
    </style>
</head>
<body>


<div class="layui-fluid">
    <div class="layui-row layui-col-space15">

        <div class="layui-col-md3">

            <div class="layui-card">
                <div class="layui-collapse">
                    <div class="layui-colla-item">
                        <h2 class="layui-colla-title"
                            style="padding:0;text-align:center;height:39px;line-height:39px;">参数分类</h2>
                        <div class="layui-colla-content layui-show">
                            <div class="input-search mb-10" style="display: none;">
                                <input type="text" class="layui-input layui-input-sm"
                                       style="border-radius: 15px;"
                                       id="jstree_left_search" name="jstree_left_search"
                                       placeholder="快速查找...">
                            </div>
                            <ul id="treeDemo" class="ztree"></ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-col-md9 layui-form-pane">
            <div class="layui-card">
                <div class="layui-card-header">系统配置</div>

                <div class="layui-form layui-card-header layuiadmin-card-header-auto">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <div class="layui-input-inline">
                                <input type="text" name="title" autocomplete="off"
                                       class="layui-input"
                                       placeholder="参数名称">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <div class="layui-input-inline">
                                <input type="text" name="name" autocomplete="off"
                                       class="layui-input"
                                       placeholder="参数编码">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <div class="layui-input-inline">
                                <input type="text" name="value" autocomplete="off"
                                       class="layui-input"
                                       placeholder="参数值">
                            </div>
                        </div>


                        <div class="layui-inline">

                            <button id="search_btn" class="layui-btn layui-btn-normal" lay-submit
                                    lay-filter="btn-search">
                                搜索
                            </button>
                            <button class="layui-btn layuiadmin-btn-list" data-type="add">添加</button>
                        </div>
                    </div>
                </div>


                <div class="layui-card-body">
                    <table class="layui-hide" id="main-table" lay-filter="main-table"></table>
                    <script type="text/html" id="test-table-operate-barDemo">
                        <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
                        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
                    </script>
                </div>
            </div>

        </div>
    </div>
</div>

<script src="{{ADMIN_PATH}}layui/layuiadmin/layui/layui.js"></script>
<script src="{{ADMIN_PATH}}ztree/js/jquery-1.4.4.min.js"></script>
<script src="{{ADMIN_PATH}}ztree/js/jquery.ztree.core.js"></script>
<script>
    var index_url = "{{url('admin/config/group')}}";
    var add_url = "{{url('admin/config/add')}}";
    var edit_url = "{{url('admin/config/edit')}}";
    var del_url = '{{url('admin/config/del')}}';
    var reload_table;
    var select_menuid;
    var search_data;
    layui.config({
        base: '{{ADMIN_PATH}}layui/layuiadmin/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['index', 'table'], function () {
        var $ = layui.$
            , admin = layui.admin
            , element = layui.element
            , form = layui.form;
        var table = layui.table;
        //====================获取访问token=======================
        var localToken = layui.data('token');

        //=========================表单搜索搜索========================
        form.on('submit(btn-search)', function (data) {

            var field = data.field;
            console.log(field);
            search_data=field;
            //
            // //执行重载
            table.reload('main-table', {
                where: field
            });
        });
        $('.layui-btn.layuiadmin-btn-list').on('click', function () {
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });
        //表格默认排序字段
        var table_sort = 'id';
        var table_order = 'desc';
        //===================表格渲染========================
        table.render({
            elem: '#main-table'
            , url: index_url
            , headers: {token: localToken.access_token}
            , method: 'post'
            , initSort: { //初始化时的排序,如果不设的话，将无法标记表头的排序状态
                field: table_sort
                , type: table_order
            }
            , where: {sort: table_sort, order: table_order}
            , cols: [[
                {field: 'id', title: 'ID', width: 80, sort: true, fixed: true}
                , {field: 'sort', title: '排序', width: 80, sort: true, fixed: true, edit: 'text'}
                , {field: 'name', title: '配置名称', width: 220, sort: true, fixed: true}
                , {field: 'title', title: '配置说明', width: 220, sort: true, fixed: true}
                , {field: 'value', title: '对应值', width: 220, sort: true, fixed: true}
                , {field: 'status', title: '状态', width: 80, sort: true, fixed: 'right', templet: temp_switch_tpl}
                , {width: 120, title: '操作', align: 'center', fixed: 'right', toolbar: '#test-table-operate-barDemo'}
            ]]
            //进行按钮操作
            , page: true
            , done: function (res, curr, count) {
                //如果是异步请求数据方式，res即为你接口返回的信息。
                //如果是直接赋值的方式，res即为：{data: [], count: 99} data为当前页数据、count为数据总长度
                // console.log(res);
                //
                // //得到当前页码
                // console.log(curr);
                //
                // //得到数据总量
                // console.log(count);
            }
        });
        // ===========================表格监听=================================================
        table.on('sort()', function (obj) { //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
            // console.log(obj.field); //当前排序的字段名
            // console.log(obj.type); //当前排序类型：desc（降序）、asc（升序）、null（空对象，默认排序）
            // reload_table.reload('main-table',{sort: {sort: obj.field, order: obj.type}});
            lzy_reload_table("main-table", {sort: {sort: obj.field, order: obj.type}});
        });
        //===========================表格编辑处理=================================================
        table.on('tool(main-table)', function (obj) { //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            var tr = obj.tr; //获得当前行 tr 的DOM对象

            if (layEvent === 'edit') { //编辑
                layer.open({
                    type: 2,
                    title: '编辑:' + data.title
                    , shade: false
                    , area: ['700px', '580px'] //宽高
                    , btn: ['确定', '取消']
                    , content: edit_url + '/' + data.id
                    , zIndex: layer.zIndex //重点1
                    , yes: function (index, layero) {
                        //点击确认触发 iframe 内容中的按钮提交
                        var submit = layero.find('iframe').contents().find("#form_save");
                        submit.click();
                    }
                    , success: function (layero) {
                        layer.setTop(layero); //重点2
                    }
                });
            } else if (layEvent === 'del') { //删除
                layer.confirm('确定删除吗?', function (index) {
                    //提交数据
                    var o = {id: data.id};
                    $.post(del_url, o, function (res) {
                        try {
                            if (res.status == 200) {
                                //重新刷新父窗口的数据区
                                reload_table.reload('main-table'); //重载表格
                            } else {
                                layer.msg(res.message);
                            }
                        } catch (e) {
                            layer.msg("异常");
                        }
                    });

                    //关闭自身提示框
                    layer.close(index);
                });
            }
        });
        form.on('switch(component-switch)', function (data) {
            layer.msg('开关checked：' + (this.checked ? 'true' : 'false'), {
                offset: '6px'
            });

        });
        //===========================外部按钮事件=====================
        var active = {
            add: function () {
                layer.open({
                    type: 2
                    , title: '新增配置'
                    , content: add_url + "?menuid=" + select_menuid
                    , maxmin: true
                    , area: ['700px', '580px'] //宽高
                    , btn: ['确定', '取消']
                    , yes: function (index, layero) {
                        //点击确认触发 iframe 内容中的按钮提交
                        var submit = layero.find('iframe').contents().find("#form_save");
                        submit.click();
                    }
                });
                return false;
            }
        };

//监听工具条
        reload_table = table;

    });
    //==============================================重新刷新表格=====================================
    function lzy_reload_table(tableid, $extend_param,page) {
        var post_data=$extend_param;
        if (!is_null(search_data) && is_json(search_data)) {
            post_data = merge_json(search_data, $extend_param);
        }
        var order_by = {};
        try {
            if (is_json(post_data.sort)) {
                order_by = post_data.sort;
            } else {
                try {
                    order_by = {
                        'sort': main_table.config.initSort.field
                        , 'order': main_table.config.initSort.type
                    };
                } catch (e) {
                    console.log(e);
                }
            }
        } catch (e) {
            console.log(e);
        }

        var o = {};

        try {
            if (is_json(order_by)) {
                o['initSort'] = {field: order_by.sort, type: order_by.order};
                post_data['sort'] = order_by.sort;
                post_data['order'] = order_by.order;
            }
        } catch (e) {
            console.log(e);
        }

        o['where'] = post_data;
        if (!is_null(page)) {
            //重新从第 N 页开始
            o['page'] = {
                curr: parseInt(page)
            };
        }
        reload_table.reload('main-table',o);
    }

    //判断obj是否为json对象
    function is_json(obj) {
        var isjson = typeof(obj) == "object" && Object.prototype.toString.call(obj).toLowerCase() == "[object object]" && !obj.length;
        return isjson;
    }

    /**
     * 判断是否null
     * @param data
     */
    function is_null(data) {
        return (data == "" || data == undefined || data == null) ? true : false;
    }
    //合并2个json
    function merge_json(json1, json2) {
        var count1 = Object.keys(json1).length;
        var count2 = Object.keys(json2).length;
        if (count1 == 0 && count2 == 0) {
            return {};
        } else if (count1 > 0 && count2 == 0) {
            return json1;
        } else if (count1 == 0 && count2 > 0) {
            return json2;
        } else {
            return eval('(' + (JSON.stringify(json1) + JSON.stringify(json2)).replace(/}{/, ',') + ')');
        }
    }
</script>

<SCRIPT type="text/javascript">
    //==========================ztree树成生成与事件================================



    var setting = {
        view: {
            nameIsHTML: true,
            showIcon: false,
            showLine: true,
            txtSelectedEnable: false,
            addDiyDom: addDiyDom
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        callback: {
            onClick: onClick
        }
    };

    var zNodes ={!! $menu_list !!};
    var className = "dark";

    //自定义节点
    function addDiyDom(treeId, treeNode) {
        var sObj = $("#" + treeNode.tId + "_span");
        var addStr = "<i class='" + treeNode.icon + "'></i>&nbsp;";
        //在节点前加入 ICON 图标
        sObj.before(addStr);
        var addStr = "&nbsp;(" + treeNode.id + ")";
        sObj.after(addStr);
    }

    function onClick(event, treeId, treeNode, clickFlag) {
        select_menuid = treeNode.id;
        reload_table.reload('main-table', {
            where: {type: treeNode.id}
        });
    }

    function getTime() {
        var now = new Date(),
            h = now.getHours(),
            m = now.getMinutes(),
            s = now.getSeconds();
        return (h + ":" + m + ":" + s);
    }

    $(document).ready(function () {
        $.fn.zTree.init($("#treeDemo"), setting, zNodes);

        var treeId = "treeDemo";
        var    treeObj = $.fn.zTree.getZTreeObj(treeId);
        treeObj.expandAll(true);
    });



    function temp_switch_tpl(d) {
        if (d.status == 1) {
            return '<input type="checkbox" name="zzz" lay-skin="switch" lay-text="开启|关闭" lay-filter="component-switch"  checked >';
        } else {
            return '<input type="checkbox" name="zzz" lay-skin="switch" lay-text="开启|关闭" lay-filter="component-switch">';
        }

    }
</SCRIPT>
</body>
</html>